<!--
 * @Author: your name
 * @Date: 2022-03-16 20:25:23
 * @LastEditTime: 2022-04-27 01:22:22
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \react-antd-admin\vue-admin-template\src\views\admin\roleList.vue
-->
<template>
  <div>
    <el-button type="primary"
               size='mini'
               @click="toAdd">新增</el-button>
    <div class="table">
      <el-table v-loading='loading'
                :data="roles"
                size='mini'
                border
                style="width: 100%">
        <el-table-column width="80px"
                         type="index"
                         :index='1'
                         label="排序号">
        </el-table-column>
        <el-table-column prop="name"
                         label="角色名称">
        </el-table-column>
        <el-table-column label="操作"
                         width="200"
                         align="center">
          <template slot-scope="scope">
            <el-button type="text"
                       size="small"
                       @click="toEdit(scope.row)">编辑</el-button>
            <el-divider direction="vertical"></el-divider>
            <el-button type="text"
                       size="small"
                       @click="toAuthorization(scope.row)">授权</el-button>
            <el-divider direction="vertical"></el-divider>
            <el-button type="text"
                       size="small"
                       @click="toDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-dialog :title="title"
               :visible.sync="visible">
      <el-form ref="role_form"
               :model="form"
               :rules="rules">
        <el-form-item label="角色名称"
                      label-width="80px"
                      prop="name">
          <el-input v-model="form.name"
                    autocomplete="off" />
        </el-form-item>
      </el-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button size="small"
                   @click="visible = false">取 消</el-button>
        <el-button type="primary"
                   size="small"
                   @click="toSaveRole">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="授权"
               :visible.sync="authorization_visible"
               width="80%">
      <el-form :model="role">
        <el-form-item label="角色名称"
                      label-width="80px">{{ role.name }}</el-form-item>
        <el-form-item label="权限"
                      label-width="80px">
          <el-cascader-panel v-model="role.privileges"
                             :options="options"
                             :props="props"
                             clearable />
        </el-form-item>
      </el-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button size="small"
                   @click="authorization_visible = false">取 消</el-button>
        <el-button type="primary"
                   size="small"
                   @click="authorizationHandler">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getFindRole, updateRole, deleteRoleById, createRole, authorizationById } from '@/api/role';
import { getPrivilegeTree } from '@/api/privilege';
let _ = require('lodash')
export default {
  data() {
    return {
      roles: [],
      loading: false,
      title: '',
      visible: false,
      form: {},
      rules: {
        name: [{
          required: true,
          message: '请输入角色名称',
          trigger: 'blur'
        }],
      },
      role: {},
      authorization_visible: false,
      options: [],
      props: {
        multiple: true,
        value: 'id',
        label: 'name',
        emitPath: false,
        checkStrictly: true,
        expandTrigger: 'hover'
      },
    };
  },
  created() {
    this.getAllRole();
    this.loadPrivileges();
  },
  mounted() {

  },
  methods: {
    async getAllRole() {
      this.loading = true;
      const res = await getFindRole();
      // 将权限转换为id的数组
      res.data.forEach((item) => {
        item.privileges = item.privileges.map((p) => {
          return p.id
        })
      })
      this.roles = res.data;
      this.loading = false;
    },
    /**
     * @description: 获取权限树
     * @param {*}
     * @return {*}
     */
    async loadPrivileges() {
      this.loading = true
      const res = await getPrivilegeTree()
      this.foo(res.data)
      this.options = res.data
      this.loading = false
    },
    toSaveRole() {
      this.$refs.role_form.validate(async (valid) => {
        if (valid) {
          let res;
          if (this.title === '添加用户信息') {
            res = await createRole({ name: this.form.name })
          }
          if (this.title === '修改用户信息') {
            res = await updateRole({ name: this.form.name, id: this.form.id })
          }
          this.$notify.success({
            title: '成功',
            message: res.message
          })
          this.getAllRole()
          this.visible = false
        } else {
          return false
        }
      })
    },
    toEdit(row) {
      this.form = { ...row }
      this.title = '修改角色信息'
      this.visible = true
    },
    toAdd() {
      this.form = {}
      this.title = '添加用户信息'
      this.visible = true
    },
    /**
     * @description:  递归去除权限中的空children
     * @param {*} privileges
     * @return {*}
     */
    foo(privileges) {
      for (const p of privileges) {
        if (p.children && p.children.length === 0) {
          delete p.children
        } else {
          this.foo(p.children)
        }
      }
    },
    /**
     * @description: 去授权
     * @param {*} row
     * @return {*}
     */
    toAuthorization(row) {
      this.role = row
      this.authorization_visible = true
    },
    async authorizationHandler() {
      if (this.role.privileges.length == 0) {
        this.role.privileges = ''
      }
      const res = await authorizationById(this.role)
      this.authorization_visible = false
      this.$message({ message: res.message, type: 'success' })
      this.getAllRole()
      this.role = {}
    },
    toDelete(id) {
      this.$confirm('此操作将永久删除该信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const res = await deleteRoleById({ id })
        this.$message({ type: 'success', message: res.message })
        this.getAllRole()
      })
    },
  }
};
</script>

<style scoped lang="less">
</style>
